<template>
  <div class="comment">
    <div class="photo-bottom">
      <div class="comment-box">
        <textarea v-model="newComment" placeholder="写点什么..." class="input-block-level comt-area" name="comment" id="comment" cols="100%" rows="3" tabindex="1" onkeydown="if(event.ctrlKey&amp;&amp;event.keyCode==13){document.getElementById('submit').click();return false};"></textarea>
        <div class="comt-ctrl">
          <mt-button size="small" class="btn btn-comment" name="submit" id="submit" tabindex="5" @click="sendMsg">
            <i class="fa fa-check-square-o"></i> 提交评论
          </mt-button>
        </div>
      </div>
      <div class="comments">
        <ol class="comment-list">
          <li v-for="(msg,index) in msgs" :key="index">
            {{msg.user_name}}：{{msg.content}} {{msg.add_time | relativeTime }}
          </li>
        </ol>
      </div>
      <mt-button type="danger" size="large" plain @click="loadMore(page)">加载更多{{page}}</mt-button>
    </div>
  </div>
</template>
<script>
export default {
  name: 'comment',
  props: ['cid'],
  data () {
    return {
      page: 1,
      msgs: [],
      newComment: ''
    }
  },
  created () {
    this.page = this.$route.query.page || '1'
    this.loadMore()
  },
  methods: {
    loadMore (page) {
      this.$axios
        .get(`getcomments/${this.cid}?pageindex=${this.page}`)
        .then(res => {
          console.log(res)
          if (res.data.message.length === 0) {
            this.$toast('没有数据了')
          }
          if (page) {
            this.msgs = this.msgs.concat(res.data.message)
          } else {
            this.msgs = res.data.message
          }
          this.page++
        })
        .catch(err => console.log('获取评论失败', err))
    },
    sendMsg () {
      // 发表之前判断是否为空
      if (this.newComment === '') {
        return this.$toast('评论不能为空！')
      }

      // 获取评论消息
      this.$axios.post(`postcomment/${this.cid}`, `content=${this.newComment}`)
        .then(res => {
          // 发表后情况评论框
          this.newComment = ''
          // 加载最新数据
          this.page = 1
          this.loadMore()
        })
        .catch(err => {
          console.log(err)
          return this.$toast('发表评论失败')
        })
    }
  }
}
</script>
<style lang="less">
.comment {
  li {
    display: block;
  }
  textarea {
    width: 100%;
  }
  .comt-ctrl {
    display: flex;
    justify-content: flex-end;
  }
  .btn-comment {
    color: #fff;
    background-color: #5fbaac;
  }
}
</style>
